package com.chookss.video;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.entity.VideoEntity;
import com.chookss.video.recommend.VedioDetailActivity;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lvgroup.hospital.base.BaseAct;
import com.makeramen.roundedimageview.RoundedImageView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;
import scut.carson_ho.searchview.EditText_Clear;

public class SearchVideoResultActivity extends BaseAct {


    @BindView(R.id.et_search)
    EditText_Clear etSearch;
    @BindView(R.id.search_cancle)
    TextView searchCancle;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.smrRf)
    SmartRefreshLayout smrRf;
    @BindView(R.id.ll_empty_view)
    LinearLayout llEmptyView;
    @BindView(R.id.llSearch)
    LinearLayout llSearch;
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.tvNone1)
    TextView tvNone1;
    @BindView(R.id.tvNone2)
    TextView tvNone2;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    private MyVedioAdapter adapter;
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private List<VideoEntity> list = new ArrayList<>();
    private String keyword;
    private int type = 0;//默认搜索结果页面 1是我的视频收藏列表  2  图文发布过来的

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_search_video_results);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        type = getIntent().getIntExtra("type", 0);
        if (type == 0 || type == 2) {
            commonTitleTxt.setText("搜索");
            llSearch.setVisibility(View.VISIBLE);
            tvNone2.setVisibility(View.VISIBLE);
            tvNone1.setText("搜索结果是空的");
            ivNone.setBackgroundResource(R.drawable.icon_default_no_search);
        } else {
            commonTitleTxt.setText("收藏");
            llSearch.setVisibility(View.GONE);
            tvNone1.setText("暂无收藏");
            ivNone.setBackgroundResource(R.drawable.icon_default_no_video);
        }

        keyword = getIntent().getStringExtra("keyword");
        etSearch.setClearIconVisible(true);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
               if(Utils.isNull(s.toString())){
                   searchCancle.setText("取消");
               }else{
                   searchCancle.setText("搜索");
               }
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        keyword = v.getText().toString();
                        HashMap<String, String> map = new HashMap<>();
                        map.put("Video_search_key", keyword);
                        EventBus.getDefault().post(new MyEvent(map));
                        isEnd = false;
                        currentPage = 1;
                        getData();
                        return false;
                    } else {
                        MyToast.show("请输入视频关键词");
                    }
                }
                return true;
            }
        });
        searchCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if("搜索".equals(searchCancle.getText().toString())){
                    keyword = etSearch.getText().toString();
                    HashMap<String, String> map = new HashMap<>();
                    map.put("Video_search_key", keyword);
                    EventBus.getDefault().post(new MyEvent(map));
                    isEnd = false;
                    currentPage = 1;
                    getData();
                }else{
                    EventBus.getDefault().post(new MyEvent("Video_search_finish"));
                    finish();
                }
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new MyVedioAdapter(R.layout.item_video_in_search_list, this, list);
        recyclerView.setAdapter(adapter);
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        smrRf.autoRefresh();
    }

    private void getData() {
        showLoading();
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
        String url = "";
        if (type == 0 || type == 2) {
            url = Urls.selectVideoByParm;
            map.put("videoParam", keyword);
        } else {
            url = Urls.getMyItemByType;
            map.put("messageType", "2");
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<VideoEntity>>>() {
        }.getType(), null, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<VideoEntity>>() {
            @Override
            public void onSuccess(List<VideoEntity> data) {
                dismissLoading();
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null || llEmptyView == null) {
                    return;
                }
                int oldIndex = list.size();
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(oldIndex, data.size());
                    smrRf.setVisibility(View.VISIBLE);
                    llEmptyView.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        smrRf.setVisibility(View.GONE);
                        llEmptyView.setVisibility(View.VISIBLE);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });


    }

    class MyVedioAdapter extends BaseQuickAdapter<VideoEntity, BaseViewHolderEx> {
        private Context context;

        public MyVedioAdapter(int layoutResId, Context context, @Nullable List<VideoEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, VideoEntity item) {

            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvTime = helper.getView(R.id.tvTime);
            TextView tvZan = helper.getView(R.id.tvZan);
            RoundedImageView ivCover = helper.getView(R.id.ivCover);
            ImageView ivZan = helper.getView(R.id.ivZan);
            tvTitle.setText(item.videoTitle);
            tvTime.setText(Utils.changeTime(item.videoSeconds));
            tvZan.setText(item.videoLikeCounts);
            GlideUtils.load(context, item.videoCoverPath, ivCover, R.drawable.default_vedio);
            if ("1".equals(item.isLike)) {
                ivZan.setBackgroundResource(R.drawable.icon_like_selected);
            } else {
                ivZan.setBackgroundResource(R.drawable.icon_like_unselected);
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if (type == 2) {
                        //图文发布过来的，要回传回去，不是打开
                        EventBus.getDefault().post(new MyEvent("Video_search_finish"));
                        Map<String, String> map = new HashMap<>();
                        map.put("url", item.videoCoverPath);
                        map.put("id", item.videoId);
                        map.put("isShare", item.shareFlag);
                        EventBus.getDefault().post(new MyEvent(map));
                        finish();
                        return;
                    }
                    VideoEntity video = item;
                    if (Utils.isNull(video.videoId) || Utils.isNull(video.id)) {
                        MyToast.show("视频id不能为空");
                        return;
                    }
                    Intent intent = null;
                    if ("2".equals(video.videoType)) {
                        intent = new Intent(SearchVideoResultActivity.this, VedioDetailActivity.class);
                        if (type == 1) {
                            intent.putExtra("watermark", "20");
                        }
                    } else {
                        intent = new Intent(SearchVideoResultActivity.this, VideoOnePlayActivity.class);
                        if (type == 1) {
                            intent.putExtra("watermark", "20");
                        } else {
                            intent.putExtra("watermark", "2");
                        }

                    }
                    intent.putExtra("video", video);
                    startActivity(intent);
                }
            });
        }
    }

    private int dex = 0;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("videoId")) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).videoId.equals(map.get("videoId"))) {
                        dex = i;
                        KLog.i(list.get(i).isLike + "---" + list.get(i).videoLikeCounts);
                        if (map.containsKey("totalCommentNum")) {
                            list.get(i).videoCommentCounts = map.get("totalCommentNum");
                        }
                        if (map.containsKey("videoShareCounts")) {
                            list.get(i).videoShareCounts = map.get("videoShareCounts");
                        }
                        if (map.containsKey("videoCollectCounts")) {
                            list.get(i).videoCollectCounts = map.get("videoCollectCounts");
                        }
                        if (map.containsKey("videoPlayCounts")) {
                            list.get(i).videoPlayCounts = map.get("videoPlayCounts");
                        }
                        if (map.containsKey("videoLikeCounts")) {
                            list.get(i).videoLikeCounts = map.get("videoLikeCounts");
                        }
                        if (map.containsKey("isCollect")) {
                            list.get(i).isCollect = map.get("isCollect");
                        }
                        if (map.containsKey("isLike")) {
                            list.get(i).isLike = map.get("isLike");
                            adapter.notifyItemChanged(i);
                        }

                    }
                }
                KLog.i(list.get(dex).isLike + "+===" + list.get(dex).videoLikeCounts);
            }
        }
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("videoId")) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).videoId.equals(map.get("videoId"))) {
                        dex = i;
                        KLog.i(list.get(i).isLike + "---" + list.get(i).videoLikeCounts);
                        if (map.containsKey("totalCommentNum")) {
                            list.get(i).videoCommentCounts = map.get("totalCommentNum");
                        }
                        if (map.containsKey("videoShareCounts")) {
                            list.get(i).videoShareCounts = map.get("videoShareCounts");
                        }
                        if (map.containsKey("videoCollectCounts")) {
                            list.get(i).videoCollectCounts = map.get("videoCollectCounts");
                        }
                        if (map.containsKey("videoLikeCounts")) {
                            list.get(i).videoLikeCounts = map.get("videoLikeCounts");
                        }
                        if (map.containsKey("videoPlayCounts")) {
                            list.get(i).videoPlayCounts = map.get("videoPlayCounts");
                        }
                        if (map.containsKey("isCollect")) {
                            list.get(i).isCollect = map.get("isCollect");
                        }
                        if (map.containsKey("isLike")) {
                            list.get(i).isLike = map.get("isLike");
                            adapter.notifyItemChanged(i);
                        }

                    }
                }
                KLog.i(list.get(dex).isLike + "+===" + list.get(dex).videoLikeCounts);
            }
        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick(R.id.common_title_back)
    public void onClick() {
        EventBus.getDefault().post(new MyEvent("Video_search_finish"));
        finish();
    }

    @Override
    public void onBackPressed() {
        EventBus.getDefault().post(new MyEvent("Video_search_finish"));
        super.onBackPressed();
    }
}
